// *************************************
// * Creator:SunnyPaine
// * DateTime:2024/08/09 10:08:56
// * Description:<Description>
// * CopyRight:
// * ***********************************

using System;
using System.Globalization;

namespace SunnyPaine.Autofac.Extension.Mvvm.Utils
{
    internal static class TypeConverterUtil
    {
        internal static object Convert(object value, Type targetType)
        {
            Type type = Nullable.GetUnderlyingType(targetType) ?? targetType;
            if (type.IsEnum && value is string)
            {
                value = Enum.Parse(type, (string)value, ignoreCase: false);
            }
            else if (value is IConvertible && !targetType.IsInstanceOfType(value))
            {
                value = System.Convert.ChangeType(value, type, CultureInfo.InvariantCulture);
            }

            if (value == null && targetType.IsValueType)
            {
                value = Activator.CreateInstance(targetType);
            }

            return value;
        }
    }
}